package com.xiaobaibai.security.handler;

import com.xiaobaibai.service.ITokenService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.token.TokenService;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 为了安全,Token验证成功后我们就刷新一个Token响应回去
 */
@Slf4j
@Component
public class TokenSuccessHandler implements AuthenticationSuccessHandler {

    @Autowired
    private ITokenService tokenService;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
                                        Authentication authentication) throws IOException, ServletException {
        //检验token是否快过期了,快过期了就更换一下
//        String token = request.getHeader("Authorization");
        //通过security全局上下文获取用户信息
        String newToken = tokenService.refreshToken(authentication);
        if(newToken!=null){//不为空就更新token
            response.setHeader("Authorization",newToken);
        }
    }

}
